// components/lyric/lyric.js
let lyricHeight = 0
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isLyricShow: {
      type: Boolean,
      value: false,
    },
    lyric: String,
  },
  // 监听数据变化
  observers: {
    lyric(lrc) {
      this._parseLyric(lrc)
    },
  },
  lifetimes: {
    ready() {
      let _this = this
      wx.getSystemInfo({
        success(res) {
          lyricHeight = res.screenWidth / 750 * 64
          _this.setData({
            scrollHeight: res.windowHeight * 0.7,
          })
        }
      })
    },
  },
  data: {
    lyricList: [],
    scrollHeight: 0,
    lyricIndex: 0,
    scrollTop: 0,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    updateTime(lyricTime) {
      let lyricList = this.data.lyricList
      if (lyricList.length == 0) {
        return
      }
      // 如果当前时间大于最后一句歌词的时间 则歌词滚动条滚到最后 且 没有歌词高亮显示
      // console.log(lyricTime, lyricList[lyricList.length - 1].time)
      if (lyricTime > lyricList[lyricList.length - 1].time) {
        if (this.data.lyricIndex != -1) {
          this.setData({
            scrollTop: lyricList.length * lyricHeight,
            lyricIndex: -1
          })
        }
      }
      for (let i = 0; i < lyricList.length; i++) {
        if (lyricTime <= lyricList[i].time) {
          this.setData({
            lyricIndex: i - 1,
            scrollTop: (i - 1) * lyricHeight
          })
          break
        }
      }
      
    },
    _parseLyric(lrc) {
      let lrcArr = lrc.split('\n')
      let lyricList = []
      lrcArr.forEach((elem) => {
        let lyricTime = elem.match(/\[(\d{2,}):(\d{2})(?:\.(\d{2,3})?)]/g)
        if (lyricTime != null) {
          let lrcValue = elem.split(lyricTime)[1]
          let time2second = lyricTime[0].match(/(\d{2,}):(\d{2})(?:\.(\d{2,3})?)/)
          let sec = parseInt(time2second[1]) * 60 + parseInt(time2second[2]) + parseInt(time2second[3]) / 1000
          lyricList.push({
            lrc: lrcValue,
            time: sec
          })
        }
      })
      this.setData({
        lyricList
      })
    },
  }
})
